package com.ldn.controller.api;

import com.google.gson.GsonBuilder;
import com.wechat.pay.java.core.notification.RequestParam;
import com.wechat.pay.java.service.payments.model.Transaction;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.ldn.basic.dispose.packet.SignatureHeader;
import com.ldn.basic.dispose.vo.WechatPayNotifyVo;
import com.ldn.basic.utils.tencent.WechatPayUtil;

import java.util.Map;

/**
 * @author 李大牛家的牛 (scafel@163.com) 
 * @createDate 2024/8/22 - 9:09
 * @description ...
 **/
@Tag(name = "腾讯相关接口")
@Slf4j
@RestController
public class TencentController {


    @PostMapping("/wechat/jsSdk/config")
    public Object jsSdkConfig(@RequestBody Map<String, String> data) {
       return null;
    }

    // 针对指定编码的微信微信支付回调
    @PostMapping("/{sysCode}/wechat/pay/jsapi/notify")
    public WechatPayNotifyVo wechatPayEnd(@PathVariable("sysCode") String sysCode, HttpServletRequest request, @RequestBody String notifyData) {
        WechatPayNotifyVo notifyVo = new WechatPayNotifyVo();
        notifyVo.setCode("FAIL");
        notifyVo.setMessage("系统基础数据错误");
        // 获取微信支付配置
        try{
            WechatPayUtil.initPayMerchant("MerchatId", "PrivateKeyPath", "MerchantSerialNumber", "ApiV3Key");
            SignatureHeader signatureHeader = getSignatureHeader(request);
            RequestParam requestParam = new RequestParam.Builder()
                    .serialNumber(signatureHeader.getSerial())
                    .nonce(signatureHeader.getNonce())
                    .signature(signatureHeader.getSignature())
                    .timestamp(signatureHeader.getTimeStamp())
                    .body(notifyData)
                    .build();
            Transaction transaction =WechatPayUtil.payNotificationParser(requestParam);
            log.info("微信支付回调数据 => {}", new GsonBuilder().setPrettyPrinting().create().toJson(transaction));
        }catch (Exception e){
            log.error("微信支付回调异常 ex => { }", e);
        }
        return notifyVo;
    }

    // 针对指定编码编码的微信微信支付回调
    @PostMapping("/{sysCode}/wechat/pay/jsapi/notify/prepay")
    public WechatPayNotifyVo wechatPrepayEnd(@PathVariable("sysCode") String sysCode,HttpServletRequest request, @RequestBody String notifyData) {
        WechatPayNotifyVo notifyVo = new WechatPayNotifyVo();
        notifyVo.setCode("FAIL");
        notifyVo.setMessage("系统基础数据错误");
        // 获取微信支付配置
        try{
            WechatPayUtil.initPayMerchant("MerchatId", "PrivateKeyPath", "MerchantSerialNumber", "ApiV3Key");
            SignatureHeader signatureHeader = getSignatureHeader(request);
            RequestParam requestParam = new RequestParam.Builder()
                    .serialNumber(signatureHeader.getSerial())
                    .nonce(signatureHeader.getNonce())
                    .signature(signatureHeader.getSignature())
                    .timestamp(signatureHeader.getTimeStamp())
                    .body(notifyData)
                    .build();
            Transaction transaction =WechatPayUtil.payNotificationParser(requestParam);
            log.info("微信支付回调数据 => {}", new GsonBuilder().setPrettyPrinting().create().toJson(transaction));
            // 支付结果记录
            notifyVo.setCode("SUCCESS");
            notifyVo.setMessage("系统记录成功!");
            if (transaction.getTradeState() == Transaction.TradeStateEnum.SUCCESS) {
                String[] type = transaction.getAttach().split("-");
                // 分类处理支付结果
            }
        }catch (Exception e){
            log.error("微信支付回调异常 ex => { }", e);
        }
        return notifyVo;
    }

    @PostMapping("/{sysCode}/wechat/pay/jsapi/notify/refund")
    public WechatPayNotifyVo wechatRefundEnd(@PathVariable("sysCode") String sysCode,HttpServletRequest request, @RequestBody String notifyData) {
        WechatPayNotifyVo notifyVo = new WechatPayNotifyVo();
        notifyVo.setCode("FAIL");
        notifyVo.setMessage("系统基础数据错误");
        // 获取微信支付配置
        try{
            WechatPayUtil.initPayMerchant("MerchatId", "PrivateKeyPath", "MerchantSerialNumber", "ApiV3Key");
            SignatureHeader signatureHeader = getSignatureHeader(request);
            RequestParam requestParam = new RequestParam.Builder()
                    .serialNumber(signatureHeader.getSerial())
                    .nonce(signatureHeader.getNonce())
                    .signature(signatureHeader.getSignature())
                    .timestamp(signatureHeader.getTimeStamp())
                    .body(notifyData)
                    .build();
            Transaction transaction =WechatPayUtil.payNotificationParser(requestParam);
            log.info("微信退款回调数据 => {}", new GsonBuilder().setPrettyPrinting().create().toJson(transaction));
            // 支付结果记录
            notifyVo.setCode("SUCCESS");
            notifyVo.setMessage("系统记录成功!");
        }catch (Exception e){
            log.error("微信退款回调异常 ex => { }", e);
        }
        return notifyVo;
    }

    public static SignatureHeader getSignatureHeader(HttpServletRequest request) {
        SignatureHeader signatureHeader = new SignatureHeader();
        signatureHeader.setSignature(request.getHeader("Wechatpay-Signature"));
        signatureHeader.setNonce(request.getHeader("Wechatpay-Nonce"));
        signatureHeader.setSerial(request.getHeader("Wechatpay-Serial"));
        signatureHeader.setTimeStamp(request.getHeader("Wechatpay-TimeStamp"));
        signatureHeader.setSignatureType(request.getHeader("Wechatpay-Signature-Type"));
        return signatureHeader;
    }


}